package com.white.hot.controller;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

import com.mysql.fabric.xmlrpc.base.Array;
import com.white.hot.constant.ConstantInfo;
import com.white.hot.dto.CrashLog;
import com.white.hot.dto.Goods;
import com.white.hot.dto.User;
import com.white.hot.dto.resp.BaseResp;
import com.white.hot.dto.resp.MapInfo;
import com.white.hot.service.CrashLogService;
import com.white.hot.service.GoodsService;
import com.white.hot.service.UserService;
import com.white.hot.utils.FileUtils;
import com.white.hot.utils.TextUtils;

@Controller
@EnableWebMvc
@RequestMapping("/upload")
public class FileUploadController extends BaseController
{
	String android = "http://service.picasso.adesk.com/v1/wallpaper/category/4e4d610cdf714d2966000000/wallpaper?limit=30&adult=false&first=1&order=new";

	@Resource
	private CrashLogService crashLogService;
	@Resource
	private UserService userService;
	@Resource
	private GoodsService goodsService;
	
	@RequestMapping(value="/uploadLog")
	@ResponseBody
	public Object uploadFile(@RequestParam("crashlog") CommonsMultipartFile log, HttpServletRequest req, HttpServletResponse response) throws IOException
	{
		String stillCrashRoot = "uploadFiles/CrashLog/";
		String crashRoot = req.getSession().getServletContext().getRealPath("uploadFiles/CrashLog");
		String h = req.getHeader("client");
		String brand = req.getHeader("Brand");
		String model = req.getHeader("DeviceModel");
		String apiCode = req.getHeader("ApiCode");
		String uid = req.getHeader("UserId");
		if(!TextUtils.isEmpty(h))
		{
			crashRoot = crashRoot + "/" + h;
			stillCrashRoot = stillCrashRoot + h + "/";
		}
		File uploadFile = new File(crashRoot);
		if(!uploadFile.exists())
		{
			uploadFile.mkdirs();
		}
		String fileName = log.getOriginalFilename();
		System.out.println(fileName);
		BaseResp resp = new BaseResp();
		if(!TextUtils.isEmpty(fileName))
		{
			InputStream fis = log.getInputStream();
			int size = fis.available();
			com.white.hot.utils.FileUtils.writeToFile(fis, crashRoot + "/" + fileName);
			CrashLog c = new CrashLog();
			c.setLogTime(sdf.format(new Date(System.currentTimeMillis())));
			c.setLogType((byte) 0);
			c.setLogName(fileName);
			c.setLogUrl(stillCrashRoot + fileName);
			c.setLogSize(size);
			c.setLogDeviceApi(apiCode);
			c.setLogDeviceBrand(brand);
			c.setLogDeviceModel(model);
			c.setLogUserId(uid);
			crashLogService.addCrashLog(c);
			buildSuccessResp(resp);
		}else
		{
			buildInnerErrorResp(resp);
		}
		return resp;
	}
	
	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	
	@RequestMapping(value="/uploadIbizhi")
	@ResponseBody
	public Object uploadIBizhi(@RequestParam("n") CommonsMultipartFile f, HttpServletRequest req, HttpServletResponse response) throws IOException
	{
		String filePath = req.getSession().getServletContext().getRealPath("/uploadFiles/IBizhi");
		File uploadFile = new File(filePath);
		if(!uploadFile.exists())
		{
			uploadFile.mkdirs();
		}
		String fileName = f.getOriginalFilename();
		System.out.println(fileName);
		BaseResp resp = new BaseResp();
		if(!TextUtils.isEmpty(fileName))
		{
			String asbPath = filePath + "/" + fileName;
			com.white.hot.utils.FileUtils.writeToFile(f.getInputStream(), asbPath);
			resp.setInfo(ConstantInfo.RSS_SUCCESS);
			resp.setStatus(ConstantInfo.RSC_SUCCESS);
		}else
		{
			resp.setInfo(ConstantInfo.RSS_INNER_ERROR);
			resp.setStatus(ConstantInfo.RSC_INNER_ERROR);
		}
		return resp;
	}	
	
//	private List<Goods> readFromFile(String string)
//	{
//		List<Goods> l = new ArrayList<Goods>();
//		File f = new File(string);
//		FileReader fr = null;
//		BufferedReader br = null;		
//		try
//		{
//			fr = new FileReader(f);
//			br = new BufferedReader(fr);
//			String s;		
//			while((s = br.readLine()) != null)
//			{
//				s = s.substring(s.lastIndexOf("("))
//			}
//		} catch (Exception e)
//		{
//			// TODO: handle exception
//		}
//		return null;
//	}

	@RequestMapping("/choose")
	private String chooseFile(HttpServletRequest resq)
	{
		return "uploadFile";
	}
	
	@RequestMapping("/list")
	private String logList(HttpServletRequest resq)
	{
		return "LogList";
	}
	
	@RequestMapping("/jumpApp")
	private String testJumpApp(HttpServletRequest resq)
	{
		return "jumpApp";
	}
	
	@RequestMapping(value="/uploadHeadImg")
	@ResponseBody
	private Object uploadImg(
			@RequestParam("img") CommonsMultipartFile img, HttpServletRequest req)
	{
		long id = Long.parseLong(req.getHeader("id"));
		BaseResp resp = new BaseResp();
		User u = userService.getUserById(id);
		String relativePath = "uploadFiles/HeadImg/" + u.suId;
		String uploadDirRealPath = req.getSession().getServletContext().getRealPath(relativePath);
		File uploadRealPath = new File(uploadDirRealPath);
		if(!uploadRealPath.exists())
		{
			//创建用户的个人头像文件夹
			uploadRealPath.mkdirs();
		}else
		{
			//如果有旧图片就删除
			String uImgPath = u.suPhoto;
			if(!TextUtils.isEmpty(uImgPath))
			{
				File oldImg = new File(uImgPath.substring(uImgPath.lastIndexOf('/')+1, uImgPath.length()));
				if(oldImg.exists())
				{
					oldImg.delete();
				}
			}
		}
		String fileName = img.getOriginalFilename();
		String rdstr = getOutTradeNo20();
		String newName = rdstr + FileUtils.getFileSuffix(fileName);
		
		try
		{
			com.white.hot.utils.FileUtils.writeToFile(img.getInputStream(), uploadRealPath + "/" + newName);
			u.suPhoto = relativePath + "/" + newName;
			userService.update(u);
			MapInfo mi = new MapInfo();
			mi.user = u;
			resp.setMapInfo(mi);
			resp.setInfo(ConstantInfo.RSS_SUCCESS);
			resp.setStatus(ConstantInfo.RSC_SUCCESS);
			return resp;
		} catch (IOException e)
		{
			e.printStackTrace();
			resp.setInfo(ConstantInfo.RSS_INNER_ERROR);
			resp.setStatus(ConstantInfo.RSC_INNER_ERROR);
			return resp;
		}
	}
}
